package org.yunshang.common.excel.utils;

import org.springframework.stereotype.Component;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Component
public class ImageUtil {
    /**
     * url转成图片并压缩
     */
    public static URL downloadAndCompress(String url, float quality) throws IOException, MalformedURLException {
        boolean isExist = checkImageExist(url);
        if (!isExist) {
            return new URL("");
        }

        File file = null;
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            file = File.createTempFile("image", "jpg");
            URL urlFile = new URL(url);
            inputStream = urlFile.openStream();
            fos = new FileOutputStream(file);

            byte[] bytes = new byte[10240];
            int bytesRead;
            while ((bytesRead = inputStream.read(bytes, 0, 10240)) != -1) {
                fos.write(bytes, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fos) {
                    fos.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 指定压缩图片的方式、参数等
        ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam imageWriteParam = new JPEGImageWriteParam(null);
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality(quality);
        imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DISABLED);

        ColorModel colorModel = ImageIO.read(file).getColorModel();
        imageWriteParam.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(32, 32)));
        FileOutputStream out;
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在");
        } else {
            BufferedImage bufferedImage = ImageIO.read(file);
            out = new FileOutputStream(file);
            imageWriter.reset();
            imageWriter.setOutput(ImageIO.createImageOutputStream(out));
            imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);
            out.flush();
            out.close();
        }
        return file.toURI().toURL();
    }
    /**
     * 判断图片数据是否正常
     * @param urlString
     */
    public static boolean checkImageExist(String urlString) {
        URL url;
        URLConnection urlConnection;
        try {
            url = new URL(urlString);
            urlConnection = url.openConnection();
            int status = ((HttpURLConnection) urlConnection).getResponseCode();
            if (status == 200) {
                return true;
            }
        } catch (Exception e1) {
            System.out.println("图片不存在!");
        }
        return false;
    }

}
